package cn.bugDance.domain.strategy.service.rule.chain.impl;

import cn.bugDance.domain.strategy.model.entity.RaffleFactorEntity;
import cn.bugDance.domain.strategy.model.entity.RuleConfigEntity;
import cn.bugDance.domain.strategy.model.valobj.StrategyConstant;
import cn.bugDance.domain.strategy.repository.IStrategyRepository;
import cn.bugDance.domain.strategy.service.rule.chain.AbstractRuleChain;
import cn.bugDance.domain.strategy.service.rule.chain.factory.RuleChainFactory;
import cn.bugDance.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;


@Component(StrategyConstant.StrategyRule.RULE_BLACKLIST)
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Slf4j
public class RuleBlackListChain extends AbstractRuleChain {

    @Resource
    private IStrategyRepository strategyRepository;


    @Override
    public RuleChainFactory.RuleChainActionEntity action(RaffleFactorEntity raffleFactorEntity) {
        Long strategyId = raffleFactorEntity.getStrategyId();
        String userId = raffleFactorEntity.getUserId();
        log.info("【策略领域层-RuleBlackListChain】: 开启黑名单责任链执行, strategyId: {}, userId: {}", strategyId, userId);

        RuleConfigEntity ruleConfigEntity = strategyRepository.queryRuleConfigRule(strategyId, StrategyConstant.StrategyRule.RULE_BLACKLIST);

        String config = ruleConfigEntity.getConfig();
        if(null != config){
            String[] var1 = config.split(Constants.COLON);
            String[] var2 = var1[1].split(Constants.SPLIT);

            if(Arrays.asList(var2).contains(userId)){
                log.info("【策略领域层-RuleBlackListChain】: 黑名单责任链拦截, strategyId: {}, userId: {}", strategyId, userId);
                return RuleChainFactory.RuleChainActionEntity.builder()
                        .strategyId(strategyId)
                        .awardId(Integer.valueOf(var1[0])).build();
            }
        }
        log.info("【策略领域层-RuleBlackListChain】: 黑名单责任链放行, strategyId: {}, userId: {}", strategyId, userId);
        return this.getNext().action(raffleFactorEntity);
    }
}
